"""扩展模块. 每个扩展在app.py里初始化"""
# from flask_apscheduler import APScheduler
from flask_bcrypt import Bcrypt
from flask_caching import Cache
from flask_httpauth import HTTPTokenAuth
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
from flask import jsonify, make_response, g
from app.weixin import Weixin


# class Scheduler(APScheduler):
#     def __new__(cls, *args, **kwargs):
#         if not hasattr(cls, '_instance'):
#             cls._instance = super().__new__(cls)
#         return cls._instance

auth = HTTPTokenAuth(scheme='Bearer')
bcrypt = Bcrypt()
cache = Cache(config={'CACHE_TYPE': 'simple'})
db = SQLAlchemy()
migrate = Migrate()
wx = Weixin()
# scheduler = Scheduler()


def roles_accepted(*roles):
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            perm = g.user.role in roles
            if perm:
                return fn(*args, **kwargs)
            return make_response(jsonify({'message': 'Unauthorized access'}), 403)
        return decorated_view
    return wrapper

